package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    //  订单结算页面显示数据控制器. detailArrayList ${totalNum} {totalAmount}
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法.
        Map<String,Object> map = this.orderService.getTrade(userId);
        //  返回result
        return Result.ok(map);
    }

    //   http://api.gmall.com/api/order/auth/submitOrder?tradeNo=null
    //  tradeNo == 防止用户无刷新重复回退提交订单.
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //        window.location.href = 'http://payment.gmall.com/pay.html?orderId=' + response.data.data
        orderInfo.setUserId(Long.parseLong(userId));
        //  获取页面传递的流水号
        String tradeNo = request.getParameter("tradeNo");
        //  调用比较方法.
        Boolean result = this.orderService.checkTradeNo(tradeNo, userId);
        if (!result){
            //  比较失败！
            return Result.fail().message("不能重复提交订单");
        }
        //  删除流水号
        this.orderService.delTradeNo(userId);

        //  声明一个异步编排：
        List<CompletableFuture> completableFutureList = new ArrayList<>();

        //  声明一个错误集合
        List<String> errorList = new ArrayList<>();

        //  校验库存： http://localhost:9001/hasStock?skuId=10221&num=2
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            //  orderDetailList = 3;
            for (OrderDetail orderDetail : orderDetailList) {

                CompletableFuture stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  调用服务层方法.
                    Boolean exist = this.orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!exist) {
                        //  比较失败！
                        errorList.add(orderDetail.getSkuId() + "库存不足！");
                    }
                },threadPoolExecutor);

                //  将这个stockCompletableFuture 对象放入集合 3个CompletableFuture 校验库存的
                completableFutureList.add(stockCompletableFuture);
                //  校验价格
                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                    //  校验价格：
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    //  实时价格：
                    BigDecimal skuPrice = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    //  比较价格：
                    if (orderPrice.compareTo(skuPrice) != 0) {
                        //  价格有变动. 购物车列表中 ---> 信息提示，比加入购物车时，降价:
                        String msg = orderPrice.compareTo(skuPrice) == 1 ? "降价" : "涨价";
                        //  变动了多少钱！
                        BigDecimal price = orderPrice.subtract(skuPrice).abs();
                        //  如果价格有变动，则更改购物车的价格！
                        //  hget key field;
                        //  hset key field value;
                        String cartKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
                        CartInfo cartInfo = (CartInfo) this.redisTemplate.opsForHash().get(cartKey, orderDetail.getSkuId().toString());
                        //  购物车显示的都是实时价格：
                        cartInfo.setSkuPrice(skuPrice);
                        this.redisTemplate.opsForHash().put(cartKey, orderDetail.getSkuId().toString(), cartInfo);
                        errorList.add(orderDetail.getSkuId() + "价格有变动" + msg + price + "元");
                    }
                },threadPoolExecutor);
                //  将这个对象放入集合  3个CompletableFuture 校验价格的
                completableFutureList.add(priceCompletableFuture);
            }
        }
        //  多任务组合：
        //  int [] arrays = new int[4];
        CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[completableFutureList.size()])).join();
        //  判断是否验证通过：
        if (errorList.size()>0){
            //  信息提示
            return Result.fail().message(StringUtils.join(errorList,","));
        }

        //  调用服务层方法.
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        //  调用清空购物车方法.
        //  orderService.delCart(userId,orderInfo.getOrderDetailList()); hdel key field;
        return Result.ok(orderId);
    }

    //  查看我的订单 带分页的！
    //  http://139.198.104.58:8200/api/order/auth/1/10?orderStatus=UNPAID
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderList(@PathVariable Long page,
                               @PathVariable Long limit,
                               HttpServletRequest request){
        //  获取userId
        String userId = AuthContextHolder.getUserId(request);
        //  获取订单状态
        String orderStatus = request.getParameter("orderStatus");
        //  创建一个Page对象
        Page<OrderInfo> orderInfoPage = new Page<>(page,limit);
        //  调用服务层方法.
        IPage<OrderInfo> infoIPage = this.orderService.getOrderList(orderInfoPage,userId,orderStatus);
        //  返回数据.
        return Result.ok(infoIPage);
    }

    //  根据订单Id 获取到订单对象
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        //  根据订单Id，查询订单+订单明细.
        return this.orderService.getOrderInfo(orderId);
        //  返回订单对象。为了展示支付信息，够用！
        //  return orderService.getById(orderId);
    }

    //  拆单控制器： 返回子订单集合.
    //  http://localhost:8204/api/order/orderSplit?orderId=xxx&=xxx
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(HttpServletRequest request){
        //  获取订单Id ---> 原始订单Id
        String orderId = request.getParameter("orderId");
        //  [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]
        String wareSkuMap = request.getParameter("wareSkuMap");
        //  获取到子订单集合{包含所有字段数据}.
        List<OrderInfo> orderInfoList = this.orderService.orderSplit(Long.parseLong(orderId),wareSkuMap);
        List<Map> mapList = new ArrayList<>();
        //  循环遍历.
        if (!CollectionUtils.isEmpty(orderInfoList)){
            mapList = orderInfoList.stream().map(orderInfo -> {
                Map map = this.orderService.initWare(orderInfo);
                return map;
            }).collect(Collectors.toList());
        }
        //  子订单集合.
        return mapList;
    }
}
